package com.syni.mdd.yhd.common.all.utils.aurora;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.DefaultResult;
import cn.jpush.api.JPushClient;
import cn.jpush.api.device.AliasDeviceListResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.syni.mdd.yhd.common.all.config.AuroraConfig;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.sjb.common.component.utils.common.utils.AppConfig;
import com.syni.mdd.yhd.common.all.service.BmsCommonService;
import com.syni.mdd.yhd.common.all.utils.MapUtils;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiAuroraPush.CommonPushDto;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className 极光推送工具类
 * @description TOO
 * @Author cfx
 * @DATE 2019/7/16 10:40
 * @VERSION 1.0
 **/
@Log4j2
public class AuroraPushUtils {
    protected static final Logger LOG = LoggerFactory.getLogger(AuroraPushUtils.class);

    protected static final String GROUP_PUSH_KEY = "2c88a01e073a0fe4fc7b167c";
    protected static final String GROUP_MASTER_SECRET = "b11314807507e2bcfdeebe2e";
    //用户端
    public static final String USER_CLIENT = "APP_USER";
    //商户端
    public static final String BUSINESS_CLIENT = "APP_BUSINESS";
    public static final String ANDROID = "android";
    public static final String IOS = "ios";
    public static final String ALL = "all";
    protected static final Map<String,Platform> clientMap = new HashMap<>();
    public static final int NOT = 1; //通知消息
    public static final int MESSAGE = 2; //自定义消息

    static {
        clientMap.put(ANDROID,Platform.android());
        clientMap.put(IOS,Platform.ios());
        clientMap.put(ALL,Platform.android_ios());
    }

    public static JPushClient getJpushClient(Integer application){
        JPushClient jpushClient = null;
        ClientConfig clientConfig = ClientConfig.getInstance();
        if(application == Constants.GENERAL_USER_ROLE_ID) {
            jpushClient = new JPushClient(AppConfig.getProperty(AuroraConfig.USER_MASTER_SECRET), AppConfig.getProperty(AuroraConfig.USER_APP_KEY), null, clientConfig);
        }else if(application == Constants.BUSINESS_ROLE_ID || application == Constants.ASSISTANT_ROLE_ID
                || application == Constants.DXSH_ROLE_ID){
            jpushClient = new JPushClient(AppConfig.getProperty(AuroraConfig.BUSINESS_MASTER_SECRET), AppConfig.getProperty(AuroraConfig.BUSINESS_APP_KEY), null, clientConfig);
        }
        return jpushClient;
    }


    public static void sendMessageToAppByAlias(String platform,String[] audAlias,String code,Object content,
                                               String alert,Map<String,Object> userData,Integer application){
        JPushClient jpushClient = getJpushClient(application);
        try {
            Map<String,String> messageBody = new HashMap<>();
            messageBody.put("code",code);
            messageBody.put("data",JSON.toJSONString(content));
            messageBody.putAll(MapUtils.toStringJsonMap(userData));
            //System.out.println(JSON.toJSONString(messageBody));
            //Message message = Message.newBuilder().setTitle(title).setContentType("json").setMsgContent(JSON.toJSONString(messageBody)).build();
            //PushResult result = jpushClient.sendPush(buildPushMessageToAlias(clientMap.get(platform),audAlias,message,alert));
            PushResult result = jpushClient.sendPush(buildPushMessageToAlias(clientMap.get(platform),audAlias,messageBody,alert));
            LOG.info("success Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.info("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }

    public static void sendCustomMessageToAppByAlias(String platform,String[] audAlias,Map content,Integer application){

        JPushClient jpushClient = getJpushClient(application);
        try {
            Map<String,String> messageBody = new HashMap<>();
            messageBody.putAll(content);
            PushResult result = jpushClient.sendPush(buildPushCustomMessageToAlias(clientMap.get(platform),audAlias,messageBody));
            LOG.info("success Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.info("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }

    public static void sendMessageToAppByAlias(String platform,String[] audAlias,String code,Object content,
                                               String alert,Integer application){
        JPushClient jpushClient = getJpushClient(application);
        try {
            Map<String,String> messageBody = new HashMap<>();
            messageBody.put("code",code);
            messageBody.put("data",JSON.toJSONString(content));
            PushResult result = jpushClient.sendPush(buildPushMessageToAlias(clientMap.get(platform),audAlias,messageBody,alert));
            LOG.info("success Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.info("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }

    public static void sendMessageToAppByAlias(String platform,String[] audAlias,Map<String,String> content,
                                               String alert,Integer application){
        JPushClient jpushClient = getJpushClient(application);
        try {
            Map<String,String> messageBody = new HashMap<>();
            messageBody.putAll(content);
            PushResult result = jpushClient.sendPush(buildPushMessageToAlias(clientMap.get(platform),audAlias,messageBody,alert));
            LOG.info("success Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.info("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }

    public static void sendMessageToAppByAlias(String platform,String[] audAlias,String code,String content,
                                               String alert,Integer application){
        JPushClient jpushClient = getJpushClient(application);
        try {
            Map<String,String> messageBody = new HashMap<>();
            messageBody.put("code",code);
            messageBody.put("data",content);
            PushResult result = jpushClient.sendPush(buildPushMessageToAlias(clientMap.get(platform),audAlias,messageBody,alert));
            LOG.info("success Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.info("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }



    /*public static void testSendPush_fromJSON() {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(PlatformNotification.class, new InterfaceAdapter<>())
                .create();
        // Since the type of DeviceType is enum, thus the value should be uppercase, same with the AudienceType.
        String payloadString = "{\"platform\":{\"all\":false,\"deviceTypes\":[\"IOS\"]},\"audience\":{\"all\":true,\"targets\":[{\"audienceType\":\"TAG_AND\",\"values\":[\"tag1\",\"tag_all\"]}]},\"notification\":{\"notifications\":[{\"soundDisabled\":false,\"badgeDisabled\":false,\"sound\":\"happy\",\"badge\":\"5\",\"contentAvailable\":false,\"alert\":\"Test from API Example - alert\",\"extras\":{\"from\":\"JPush\"},\"type\":\"cn.jpush.api.push.model.notification.IosNotification\"}]},\"message\":{\"msgContent\":\"Test from API Example - msgContent\"},\"options\":{\"sendno\":1429488213,\"overrideMsgId\":0,\"timeToLive\":-1,\"apnsProduction\":true,\"bigPushDuration\":0}}";
        PushPayload payload = gson.fromJson(payloadString, PushPayload.class);
        try {
            PushResult result = jpushClient.sendPush(payloadString);
            LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            // LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            //LOG.error("Sendno: " + payload.getSendno());
        }
    }*/

    public static PushPayload buildPushMessageToAlias(Platform platform,String[] audAlias,Message message,String alert) {
        return PushPayload.newBuilder()
                .setPlatform(platform)
                .setAudience(Audience.alias(audAlias))
                .setMessage(message)
                .setNotification(Notification.alert(alert))
                .build();
    }

    public static PushPayload buildPushMessageToAlias(Platform platform,String[] audAlias,Map<String,String> message,String alert) {
        String run = AppConfig.getProperty("jiguang.run");
        Map<String,Boolean> activeMap = new HashMap<>();
        activeMap.put("debug",false);
        activeMap.put("pro",true);
        return PushPayload.newBuilder()
                .setPlatform(platform)
                .setAudience(Audience.alias(audAlias))
                .setNotification(Notification.newBuilder().
                        addPlatformNotification(IosNotification.newBuilder().setAlert(alert).addExtras(message).build())
                        .addPlatformNotification(AndroidNotification.newBuilder().setAlert(alert).addExtras(message).build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(activeMap.get(run))
                        .build())
                .build();
    }

    public static PushPayload buildPushCustomMessageToAlias(Platform platform,String[] audAlias,Map<String,String> message) {
        String run = AppConfig.getProperty("jiguang.run");
        Map<String,Boolean> activeMap = new HashMap<>();
        activeMap.put("debug",false);
        activeMap.put("pro",true);
        return PushPayload.newBuilder()
                .setPlatform(platform)
                .setAudience(Audience.alias(audAlias))
                .setMessage(Message.newBuilder().setMsgContent("").addExtras(message).build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(activeMap.get(run))
                        .build())
                .build();
    }

    public static PushPayload buildPushMessageToTags(Platform platform,String[] audTags,Message message) {
        return PushPayload.newBuilder()
                .setPlatform(platform)
                .setAudience(Audience.tag(audTags))
                .setMessage(message)
                .build();
    }

    public static void main(String[] args){
        String a = "{\\\"code\\\":\\\"10000\\\",\\\"data\\\":{\\\"bmsUserId\\\":693,\\\"bmsVideoId\\\":415,\\\"childType\\\":1,\\\"fromOrigin\\\":1,\\\"id\\\":1569,\\\"isNoRead\\\":0,\\\"newTime\\\":1565661327000,\\\"opUserId\\\":788,\\\"parentType\\\":1,\\\"updateTime\\\":1565662532110,\\\"userLikeNum\\\":41,\\\"userList\\\":[{\\\"loginName\\\":\\\"\\U4f5b\\U946b\\U6d4b\\U8bd5\\U53f7\\\",\\\"userid\\\":788},{\\\"loginName\\\":\\\"\\U5e97\\U8001\\U677f\\\",\\\"userid\\\":624},{\\\"loginName\\\":\\\"yugt\\\",\\\"userid\\\":626}],\\\"videoImg\\\":\\\"http://1254456672.vod2.myqcloud.com/ea06baecvodcq1254456672/e3b6694e5285890790751437513/5285890790751437514.jpg\\\",\\\"videoName\\\":\\\"\\U4e45\\U4e45\\U867e\\U4e00\\U9505\\\"}}";
        Map<String,Object> objectMap = (Map<String, Object>) JSON.parse(a);
        System.out.println(objectMap);
    }


    public static List<String> selectAllAliases() {
        JPushClient jpushClient = getJpushClient(1);
        try {
            AliasDeviceListResult aliasDeviceListResult = jpushClient.getAliasDeviceList("U487","android");
            return aliasDeviceListResult.registration_ids;
        } catch (APIConnectionException e) {
            log.error(e.getMessage(),e);
        } catch (APIRequestException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public static boolean deleteAllAliases() {
        JPushClient jpushClient = getJpushClient(4);
        try {
            DefaultResult aliasDeviceListResult = jpushClient.deleteAlias("B_DXSH_5698","ios");
            return aliasDeviceListResult.isResultOK();
        } catch (APIConnectionException e) {
            log.error(e.getMessage(),e);
        } catch (APIRequestException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public static void pushCommonCustomMessage(CommonPushDto commonPushDto) {
        List<String> alias = JSON.parseArray(commonPushDto.getAlias(),String.class);
        String[] userAlias = alias.toArray(new String[alias.size()]);
        if(commonPushDto.getJiPushType() == MESSAGE) {
            Map<String,String> messageBody = (Map<String, String>) JSON.parse(commonPushDto.getContent());
            BmsCommonService.pushCustomMessageToFront(messageBody,userAlias,commonPushDto.getPushApplication());
        }else if(commonPushDto.getJiPushType() == NOT){
            Map<String,String> messageBody = (Map<String, String>) JSON.parse(commonPushDto.getContent());
            AuroraPushUtils.sendMessageToAppByAlias(AuroraPushUtils.ALL,userAlias,messageBody,
                    commonPushDto.getAlert(),commonPushDto.getPushApplication());
        }

    }
}
